package icraf.common.util;

import java.io.File;
import java.io.FilenameFilter;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;

public class CommonFileFilter extends FileFilter implements FilenameFilter {
	public String description = "";
	public String extension = "*";

	public CommonFileFilter(String des, String ext) {
		description = des;
		extension = ext;
	}

	@Override
	public boolean accept(File f) {
		if (f.isDirectory()) {
			return true;
		}
		if (isExtension(f.getName(), extension)) {
			return true;
		}
		return false;
	}

	@Override
	public String getDescription() {
		return description;
	}

	public String getFilterExtension() {
		return extension;
	}

	public boolean accept(File dir, String name) {
		if (dir.isDirectory() && isExtension(name, extension)) {
			return true;
		}
		return false;
	}

	public static File getValidatedFile(JFileChooser fileChooser,
			CommonFileFilter defaultFilter) {
		File file = fileChooser.getSelectedFile();
		CommonFileFilter ext;
		FileFilter ff = fileChooser.getFileFilter();
		if (ff.equals(fileChooser.getAcceptAllFileFilter())) {
			ext = defaultFilter;
		} else {
			ext = (CommonFileFilter) fileChooser.getFileFilter();
		}
		if (getExtension(file.getName()) == null) {
			File f = new File(file.getParent(), file.getName() + "."
					+ ext.getFilterExtension());
			file = f;
		}
		return file;
	}

	public static String getExtension(String f) {
		String ext = null;
		String s = f;
		int i = s.lastIndexOf('.');
		if (i > 0 && i < s.length() - 1) {
			ext = s.substring(i + 1).toLowerCase();
		}
		return ext;
	}

	private static boolean isExtension(String f, String ext) {
		if (ext.equalsIgnoreCase(getExtension(f))) {
			return true;
		} else {
			return false;
		}
	}
}
